﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;

namespace YaAppoint.EntityFrameworkCore;

/* This class is needed for EF Core console commands
 * (like Add-Migration and Update-Database commands) */
public class YaAppointDbContextFactory : IDesignTimeDbContextFactory<YaAppointDbContext>
{
    public YaAppointDbContext CreateDbContext(string[] args)
    {
        var configuration = BuildConfiguration(); 
        YaAppointEfCoreEntityExtensionMappings.Configure(); // 配置额外属性的数据库映射
        var builder = new DbContextOptionsBuilder<YaAppointDbContext>();
        if (configuration["ConnectionStrings:DbType"] == "MySql")
        {

            builder.UseMySql(configuration.GetConnectionString("Default"), new MySqlServerVersion(new Version(8, 4, 1)));
        }
        else
        {
            builder.UseSqlServer(configuration.GetConnectionString("Default"));
        }
      
        
        return new YaAppointDbContext(builder.Options);
    }
    
    // 获取IConfigurationRoot服务
    private static IConfigurationRoot BuildConfiguration()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../YaAppoint.DbMigrator/"))
            .AddJsonFile("appsettings.json", optional: false);

        return builder.Build();
    }
}
